#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
主窗口模块 - 应用程序主界面
"""

import logging
import os
from typing import Dict, List, Any, Optional
from PyQt5.QtWidgets import (
    QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, 
    QTreeView, QTableView, QPushButton, QAction, 
    QToolBar, QStatusBar, QMessageBox, QFileDialog,
    QLabel, QSplitter, QMenu, QInputDialog, QTextEdit, QGroupBox
)
from PyQt5.QtCore import Qt, QSize, pyqtSlot, QModelIndex
from PyQt5.QtGui import QIcon, QFont, QStandardItemModel, QStandardItem

from src.zabbix_api import ZabbixAPI
from gui.login_dialog import LoginDialog
from gui.host_group_model import HostGroupModel
from gui.host_table_model import HostTableModel
from gui.item_dialog import ItemDialog
from gui.trigger_dialog import TriggerDialog
from gui.mod_hostname_dialog import ModHostnameDialog
from gui.grafana_export_dialog import GrafanaExportDialog

logger = logging.getLogger(__name__)

# 创建一个日志处理器，将日志输出到UI
class UILogHandler(logging.Handler):
    def __init__(self, text_edit):
        super().__init__()
        self.text_edit = text_edit
        self.setFormatter(logging.Formatter('[%(asctime)s] [%(levelname)s] %(message)s', '%H:%M:%S'))
        
    def emit(self, record):
        msg = self.format(record)
        self.text_edit.append(msg)
        # 自动滚动到底部
        self.text_edit.verticalScrollBar().setValue(
            self.text_edit.verticalScrollBar().maximum()
        )

class MainWindow(QMainWindow):
    """应用程序主窗口"""
    
    def __init__(self, config: Dict[str, Any]):
        """
        初始化主窗口
        
        Args:
            config (Dict[str, Any]): 配置信息
        """
        super().__init__()
        self.config = config
        self.api = None
        
        # 添加数据缓存属性
        self.hosts_cache = {}  # 主机数据缓存 {group_id: hosts_list}
        self.host_ips_cache = {}  # 主机IP缓存 {hostid: [ip_list]}
        self.host_ports_cache = {}  # 主机端口缓存 {hostid: [port_list]}
        self.all_hosts_cache = {}  # 所有主机的缓存 {hostid: host_data}
        self.groups_cache = None  # 所有主机群组的缓存
        
        self.setup_ui()
        self.show_login_dialog()
    
    def setup_ui(self):
        """设置UI界面"""
        # 设置窗口基本属性
        self.setWindowTitle(self.config["app"]["name"])
        self.setMinimumSize(1200, 800)
        
        # 创建中央部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 创建主布局
        main_layout = QVBoxLayout(central_widget)
        
        # 创建主要内容容器
        main_content = QWidget()
        main_content_layout = QVBoxLayout(main_content)
        main_content_layout.setContentsMargins(0, 0, 0, 0)  # 减少边距以利用更多空间
        
        # 创建分割窗口
        splitter = QSplitter(Qt.Horizontal)
        
        # 创建左侧主机群组面板
        group_panel = QWidget()
        group_layout = QVBoxLayout(group_panel)
        group_label = QLabel("主机群组")
        group_label.setFont(QFont("Arial", 12, QFont.Bold))
        group_layout.addWidget(group_label)
        
        # 创建树状视图用于显示主机群组
        self.group_tree = QTreeView()
        self.group_tree.setHeaderHidden(True)
        self.group_tree.clicked.connect(self.on_group_selected)
        group_layout.addWidget(self.group_tree)
        
        # 将主机群组面板添加到分割窗口
        splitter.addWidget(group_panel)
        
        # 创建右侧主机面板
        host_panel = QWidget()
        host_layout = QVBoxLayout(host_panel)
        host_label = QLabel("主机列表")
        host_label.setFont(QFont("Arial", 12, QFont.Bold))
        host_layout.addWidget(host_label)
        
        # 创建表格视图用于显示主机列表
        self.host_table = QTableView()
        self.host_table.setSelectionBehavior(QTableView.SelectRows)
        self.host_table.setSelectionMode(QTableView.MultiSelection)
        host_layout.addWidget(self.host_table)
        
        # 创建按钮面板
        button_layout = QHBoxLayout()
        self.select_all_btn = QPushButton("全选")
        self.select_all_btn.clicked.connect(self.on_select_all)
        self.deselect_all_btn = QPushButton("取消选择")
        self.deselect_all_btn.clicked.connect(self.on_deselect_all)
        self.create_items_btn = QPushButton("创建监控项")
        self.create_items_btn.clicked.connect(self.on_create_items)
        self.create_triggers_btn = QPushButton("创建触发器")
        self.create_triggers_btn.clicked.connect(self.on_create_triggers)
        self.mod_hostname_btn = QPushButton("批量修改主机名")
        self.mod_hostname_btn.clicked.connect(self.on_mod_hostname)
        self.grafana_btn = QPushButton("导出用户到Grafana")
        self.grafana_btn.clicked.connect(self.on_export_to_grafana)
        
        button_layout.addWidget(self.select_all_btn)
        button_layout.addWidget(self.deselect_all_btn)
        button_layout.addWidget(self.create_items_btn)
        button_layout.addWidget(self.create_triggers_btn)
        button_layout.addWidget(self.mod_hostname_btn)
        button_layout.addWidget(self.grafana_btn)
        host_layout.addLayout(button_layout)
        
        # 将主机面板添加到分割窗口
        splitter.addWidget(host_panel)
        
        # 设置分割窗口的比例 - 扩大左侧主机群组区域宽度
        # 原始比例为[300, 900]，现在将左侧扩大约0.8倍
        splitter.setSizes([540, 660])  # 调整后的比例
        
        # 添加分割窗口到主内容布局
        main_content_layout.addWidget(splitter)
        
        # 将主内容区域添加到主布局，并设置其占比为3，从而实现上方区域扩大
        main_layout.addWidget(main_content, 3)
        
        # 日志显示区域
        log_group = QGroupBox("操作日志")
        log_layout = QVBoxLayout(log_group)
        log_layout.setContentsMargins(5, 5, 5, 5)  # 减少内边距
        
        # 创建日志显示区和清除按钮的水平布局
        log_header_layout = QHBoxLayout()
        
        self.log_text = QTextEdit()
        self.log_text.setReadOnly(True)
        # 设置等宽字体以便更好地显示日志
        font = QFont("Courier New")
        font.setPointSize(9)
        self.log_text.setFont(font)
        # 设置为白底黑字，提高可读性
        self.log_text.setStyleSheet("background-color: white; color: black;")
        log_layout.addWidget(self.log_text)
        
        # 清除日志按钮
        clear_btn = QPushButton("清除日志")
        clear_btn.clicked.connect(self.clear_log)
        clear_btn.setMaximumWidth(100)  # 限制按钮宽度
        log_layout.addWidget(clear_btn, 0, Qt.AlignRight)  # 按钮靠右对齐
        
        # 将日志区域添加到主布局，并设置其占比为1，实现下移三分之一
        main_layout.addWidget(log_group, 1)
        
        # 设置UI日志处理器
        ui_handler = UILogHandler(self.log_text)
        ui_handler.setLevel(logging.INFO)
        logger.addHandler(ui_handler)
        
        # 添加日志初始信息
        self.log_message("程序启动，等待登录...")
        
        # 创建菜单
        self.create_menus()
        
        # 创建状态栏
        self.status_bar = QStatusBar()
        self.setStatusBar(self.status_bar)
        self.status_bar.showMessage("就绪")
    
    def log_message(self, message):
        """记录日志消息"""
        logger.info(message)
    
    def clear_log(self):
        """清除日志"""
        self.log_text.clear()
        self.log_message("日志已清除")
    
    def create_menus(self):
        """创建菜单栏"""
        # 创建菜单栏
        menu_bar = self.menuBar()
        
        # 文件菜单
        file_menu = menu_bar.addMenu("文件")
        
        # 登录操作
        login_action = QAction("登录", self)
        login_action.triggered.connect(self.show_login_dialog)
        file_menu.addAction(login_action)
        
        # 退出操作
        exit_action = QAction("退出", self)
        exit_action.triggered.connect(self.close)
        file_menu.addAction(exit_action)
        
        # 操作菜单
        action_menu = menu_bar.addMenu("操作")
        
        # 刷新数据
        refresh_action = QAction("刷新数据", self)
        refresh_action.triggered.connect(self.refresh_data)
        action_menu.addAction(refresh_action)
        
        # 创建监控项
        create_items_action = QAction("创建监控项", self)
        create_items_action.triggered.connect(self.on_create_items)
        action_menu.addAction(create_items_action)
        
        # 创建触发器
        create_triggers_action = QAction("创建触发器", self)
        create_triggers_action.triggered.connect(self.on_create_triggers)
        action_menu.addAction(create_triggers_action)
        
        # 工具菜单
        tools_menu = menu_bar.addMenu("工具")
        
        # 批量修改主机名
        mod_hostname_action = QAction("批量修改主机名", self)
        mod_hostname_action.triggered.connect(self.on_mod_hostname)
        tools_menu.addAction(mod_hostname_action)
        
        # Grafana用户导出
        grafana_action = QAction("同步用户至Grafana", self)
        grafana_action.triggered.connect(self.on_export_to_grafana)
        tools_menu.addAction(grafana_action)
        
        # 帮助菜单
        help_menu = menu_bar.addMenu("帮助")
        
        # 关于操作
        about_action = QAction("关于", self)
        about_action.triggered.connect(self.show_about_dialog)
        help_menu.addAction(about_action)
    
    def show_login_dialog(self):
        """显示登录对话框"""
        self.log_message("正在打开登录对话框...")
        dialog = LoginDialog(self.config)
        if dialog.exec_():
            # 用户点击了确定按钮
            url = dialog.url_edit.text()
            user = dialog.user_edit.text()
            password = dialog.password_edit.text()
            
            self.log_message(f"正在连接到 {url}...")
            
            # 创建API客户端
            try:
                self.api = ZabbixAPI(url, user, password)
                if self.api.auth:
                    self.status_bar.showMessage(f"已连接到 {url}")
                    self.log_message(f"成功连接到 {url}")
                    
                    # 登录成功后保存配置
                    from src.config import save_config
                    save_config(self.config)
                    self.log_message("配置已保存")
                    
                    # 刷新数据并启用功能
                    self.refresh_data()
                else:
                    self.log_message("登录失败: 无法连接到Zabbix API")
                    QMessageBox.critical(self, "登录失败", "无法连接到Zabbix API，请检查配置。")
            except Exception as e:
                self.log_message(f"登录失败: {str(e)}")
                logger.error(f"连接Zabbix API失败: {e}")
                QMessageBox.critical(self, "登录失败", f"无法连接到Zabbix API: {e}")
    
    def refresh_data(self):
        """刷新数据"""
        if not self.api:
            QMessageBox.warning(self, "未连接", "请先连接到Zabbix服务器")
            return
        
        try:
            self.log_message("正在刷新数据...")
            
            # 清除所有缓存
            self.hosts_cache.clear()
            self.host_ips_cache.clear()
            self.host_ports_cache.clear()
            self.all_hosts_cache.clear()
            self.groups_cache = None
            
            # 获取主机群组 - 修复方法名
            try:
                # 尝试不同的方法名
                if hasattr(self.api, 'get_host_groups'):
                    groups = self.api.get_host_groups()
                    self.log_message("使用 api.get_host_groups() 获取主机组")
                elif hasattr(self.api, 'hostgroup') and hasattr(self.api.hostgroup, 'get'):
                    groups = self.api.hostgroup.get(output="extend")
                    self.log_message("使用 api.hostgroup.get() 获取主机组")
                elif hasattr(self.api, 'get'):
                    groups = self.api.get('hostgroup', {'output': 'extend'})
                    self.log_message("使用 api.get('hostgroup') 获取主机组")
                elif hasattr(self.api, 'do_request'):
                    response = self.api.do_request('hostgroup.get', {
                        'output': 'extend'
                    })
                    if isinstance(response, dict) and "result" in response:
                        groups = response["result"]
                    else:
                        groups = response
                    self.log_message("使用 api.do_request() 获取主机组")
                else:
                    # 直接使用JSON-RPC调用
                    import requests
                    url = getattr(self.api, 'url', getattr(self.api, 'api_url', None))
                    auth = getattr(self.api, 'auth', None)
                    
                    if url and auth:
                        json_request = {
                            "jsonrpc": "2.0",
                            "method": "hostgroup.get",
                            "params": {
                                "output": "extend"
                            },
                            "auth": auth,
                            "id": 1
                        }
                        headers = {'Content-Type': 'application/json-rpc'}
                        r = requests.post(url, json=json_request, headers=headers)
                        response = r.json()
                        groups = response.get("result", [])
                        self.log_message("使用直接HTTP请求获取主机组")
                    else:
                        raise Exception("无法获取API URL或认证信息")
            except Exception as e:
                self.log_message(f"获取主机组失败: {str(e)}")
                raise e
            
            self.groups_cache = groups  # 缓存主机群组
            self.display_host_groups(groups)
            
            # 清空主机列表
            model = HostTableModel([], ip_cache={})
            self.host_table.setModel(model)
            
            self.status_bar.showMessage("数据已刷新")
            self.log_message("数据刷新完成")
        except Exception as e:
            self.log_message(f"刷新数据失败: {str(e)}")
            logger.error(f"刷新数据失败: {e}")
            QMessageBox.critical(self, "刷新失败", f"无法刷新数据: {e}")
    
    def display_host_groups(self, groups: List[Dict[str, Any]]):
        """
        显示主机群组
        
        Args:
            groups (List[Dict[str, Any]]): 主机群组列表
        """
        # 创建主机群组模型
        model = HostGroupModel(groups)
        self.group_tree.setModel(model)
        self.group_tree.expandAll()
    
    @pyqtSlot(QModelIndex)
    def on_group_selected(self, index: QModelIndex):
        """
        当主机群组被选中时的处理函数
        
        Args:
            index (QModelIndex): 被选中的索引
        """
        if not self.api:
            return
        
        # 获取选中的群组ID
        item = self.group_tree.model().itemFromIndex(index)
        if not item:
            return
        
        group_id = item.data()
        if not group_id:
            return
        
        try:
            self.log_message(f"加载主机组ID {group_id} 的主机...")
            
            # 检查缓存中是否已有该群组的主机数据
            if group_id in self.hosts_cache:
                self.log_message(f"使用缓存数据，加载主机组ID {group_id} 的主机...")
                hosts = self.hosts_cache[group_id]
            else:
                # 从API获取主机数据
                self.log_message(f"从API获取主机组ID {group_id} 的主机...")
                hosts = self.api.get_hosts_by_group_ids([group_id])
                
                # 将获取到的主机添加到缓存
                self.hosts_cache[group_id] = hosts
                
                # 更新全局主机缓存
                for host in hosts:
                    hostid = host.get("hostid")
                    if hostid:
                        self.all_hosts_cache[hostid] = host
                
                # 获取主机接口信息
                self.fetch_host_interfaces(hosts)
            
            # 为每个主机添加group_id属性，以便显示在表格中
            for host in hosts:
                host["group_id"] = group_id
                
            # 显示主机列表 - 传递IP缓存和端口缓存
            model = HostTableModel(hosts, ip_cache=self.host_ips_cache, port_cache=self.host_ports_cache)
            self.host_table.setModel(model)
            
            # 调整列宽 - 设置更合理的比例
            self.host_table.setColumnWidth(0, 100)  # 主机群组id
            self.host_table.setColumnWidth(1, 150)  # IP地址列
            self.host_table.setColumnWidth(2, 150)  # 主机名列(技术名称)
            self.host_table.setColumnWidth(3, 150)  # 可见名称列
            self.host_table.setColumnWidth(4, 80)   # 状态列
            self.host_table.setColumnWidth(5, 80)   # 端口号列
            
            # 为表头添加工具提示，说明端口号含义
            header = self.host_table.horizontalHeader()
            header.setToolTip("端口10050: Zabbix Agent (绿色标识)\n端口161: SNMP设备 (蓝色标识)")
            
            self.status_bar.showMessage(f"找到 {len(hosts)} 台主机")
            self.log_message(f"成功加载 {len(hosts)} 台主机")
        except Exception as e:
            self.log_message(f"获取主机列表失败: {str(e)}")
            logger.error(f"获取主机列表失败: {e}")
            QMessageBox.critical(self, "获取失败", f"无法获取主机列表: {e}")
    
    def fetch_host_interfaces(self, hosts):
        """
        获取主机的接口信息，包括IP地址和端口
        
        Args:
            hosts (List[Dict[str, Any]]): 主机列表
        """
        try:
            # 提取尚未获取IP的主机ID
            hostids_to_fetch = []
            for host in hosts:
                hostid = host.get("hostid")
                if hostid and (hostid not in self.host_ips_cache or hostid not in self.host_ports_cache):
                    hostids_to_fetch.append(hostid)
            
            if not hostids_to_fetch:
                self.log_message("所有主机接口信息已在缓存中")
                return
            
            self.log_message(f"正在获取 {len(hostids_to_fetch)} 台主机的接口信息...")
            
            # 使用hostinterface.get API获取主机接口
            try:
                # 尝试不同的API调用方式获取主机接口
                if hasattr(self.api, 'hostinterface') and hasattr(self.api.hostinterface, 'get'):
                    interfaces = self.api.hostinterface.get(
                        hostids=hostids_to_fetch,
                        output="extend"
                    )
                    self.log_message("使用 api.hostinterface.get() 获取主机接口")
                else:
                    # 使用JSON-RPC格式直接调用
                    json_request = {
                        "jsonrpc": "2.0",
                        "method": "hostinterface.get",
                        "params": {
                            "output": "extend",
                            "hostids": hostids_to_fetch
                        },
                        "auth": self.api.auth,
                        "id": 1
                    }
                    
                    if hasattr(self.api, 'do_request'):
                        interfaces_resp = self.api.do_request('hostinterface.get', {
                            'hostids': hostids_to_fetch,
                            'output': "extend"
                        })
                        if isinstance(interfaces_resp, dict) and "result" in interfaces_resp:
                            interfaces = interfaces_resp["result"]
                        else:
                            interfaces = interfaces_resp
                        self.log_message("使用 api.do_request() 获取主机接口")
                    else:
                        # 直接使用API对象的auth和url属性
                        import requests
                        url = getattr(self.api, 'url', self.api.api_url if hasattr(self.api, 'api_url') else None)
                        auth = getattr(self.api, 'auth', None)
                        
                        if url and auth:
                            headers = {'Content-Type': 'application/json-rpc'}
                            json_request["auth"] = auth
                            r = requests.post(url, json=json_request, headers=headers)
                            response = r.json()
                            interfaces = response.get("result", [])
                            self.log_message("使用直接HTTP请求获取主机接口")
                        else:
                            self.log_message("无法获取API URL或认证信息")
                            return
                
                # 处理接口数据
                if interfaces:
                    self.log_message(f"找到 {len(interfaces)} 个主机接口")
                    
                    # 处理接口数据，建立主机ID到IP和端口的映射
                    for interface in interfaces:
                        hostid = interface.get('hostid')
                        ip = interface.get('ip')
                        port = interface.get('port')
                        
                        # 存储IP地址
                        if hostid and ip:
                            if hostid not in self.host_ips_cache:
                                self.host_ips_cache[hostid] = []
                            if ip not in self.host_ips_cache[hostid]:
                                self.host_ips_cache[hostid].append(ip)
                        
                        # 存储端口信息
                        if hostid and port:
                            # 更新全局主机缓存中的端口信息
                            if hostid in self.all_hosts_cache:
                                self.all_hosts_cache[hostid]['port'] = port
                                
                                # 根据端口判断设备类型
                                if port == "10050":
                                    self.all_hosts_cache[hostid]['agent_type'] = "zabbix"
                                elif port == "161":
                                    self.all_hosts_cache[hostid]['agent_type'] = "snmp"
                            
                            # 更新端口缓存
                            if hostid not in self.host_ports_cache:
                                self.host_ports_cache[hostid] = []
                            if port not in self.host_ports_cache[hostid]:
                                self.host_ports_cache[hostid].append(port)
                    
                    self.log_message(f"处理完成，获取了 {len(self.host_ips_cache)} 台主机的IP地址和 {len(self.host_ports_cache)} 台主机的端口信息")
                else:
                    self.log_message("未找到任何主机接口")
            except Exception as interface_err:
                self.log_message(f"通过API获取主机接口信息失败: {str(interface_err)}")
                logger.error(f"获取主机接口失败: {interface_err}")
        except Exception as e:
            self.log_message(f"获取主机接口信息时出错: {str(e)}")
            logger.error(f"获取主机接口信息失败: {e}")
    
    @pyqtSlot()
    def on_select_all(self):
        """全选主机"""
        if not self.host_table.model():
            return
        
        self.host_table.selectAll()
        self.log_message("已全选主机")
    
    @pyqtSlot()
    def on_deselect_all(self):
        """取消选择所有主机"""
        if not self.host_table.model():
            return
        
        self.host_table.clearSelection()
        self.log_message("已取消选择所有主机")
    
    @pyqtSlot()
    def on_create_items(self):
        """创建监控项"""
        if not self.check_api_connected():
            return
        
        # 获取选中的主机
        selected_indexes = self.host_table.selectionModel().selectedRows()
        if not selected_indexes:
            self.log_message("未选择主机，无法创建监控项")
            QMessageBox.warning(self, "未选择主机", "请先选择需要创建监控项的主机。")
            return
        
        # 获取选中主机的ID和名称 - 修复索引问题
        model = self.host_table.model()
        selected_hosts = []
        for index in selected_indexes:
            row = index.row()
            # 使用主机名称列(索引3)获取主机名称
            host_name = model.data(model.index(row, 3), Qt.DisplayRole)
            # 使用UserRole获取主机ID
            host_id = model.hosts[row].get("hostid")
            if host_id:
                selected_hosts.append({"hostid": host_id, "name": host_name})
        
        self.log_message(f"正在打开监控项配置对话框，选中了 {len(selected_hosts)} 台主机")
        # 显示监控项配置对话框
        dialog = ItemDialog(self.api, selected_hosts)
        dialog.exec_()
        self.log_message("关闭监控项配置对话框")
    
    @pyqtSlot()
    def on_create_triggers(self):
        """创建触发器"""
        if not self.check_api_connected():
            return
        
        # 获取选中的主机
        selected_indexes = self.host_table.selectionModel().selectedRows()
        if not selected_indexes:
            self.log_message("未选择主机，无法创建触发器")
            QMessageBox.warning(self, "未选择主机", "请先选择需要创建触发器的主机。")
            return
        
        # 获取选中主机的ID和名称 - 修复索引问题
        model = self.host_table.model()
        selected_hosts = []
        for index in selected_indexes:
            row = index.row()
            # 使用主机名称列(索引3)获取主机名称
            host_name = model.data(model.index(row, 3), Qt.DisplayRole)
            # 使用UserRole获取主机ID
            host_id = model.hosts[row].get("hostid")
            if host_id:
                selected_hosts.append({"hostid": host_id, "name": host_name})
        
        self.log_message(f"正在打开触发器配置对话框，选中了 {len(selected_hosts)} 台主机")
        # 显示触发器配置对话框
        dialog = TriggerDialog(self.api, selected_hosts)
        dialog.exec_()
        self.log_message("关闭触发器配置对话框")
    
    def on_mod_hostname(self):
        """批量修改主机名"""
        # 检查API连接
        if not self.check_api_connected():
            return
        
        self.log_message("正在打开批量修改主机名对话框...")
        try:
            # 创建对话框
            dialog = ModHostnameDialog(self.api)
            dialog.exec_()
            self.log_message("关闭批量修改主机名对话框")
        
        except Exception as e:
            error_msg = f"启动主机名修改对话框时发生错误：{str(e)}"
            self.log_message(error_msg)
            QMessageBox.critical(
                self,
                "错误",
                error_msg
            )
            logger.error(error_msg)
    
    def on_export_to_grafana(self):
        """导出用户到Grafana"""
        # 检查API连接
        if not self.check_api_connected():
            return
        
        self.log_message("正在打开Grafana用户导出对话框...")
        try:
            # 创建对话框
            dialog = GrafanaExportDialog(self.api)
            dialog.exec_()
            self.log_message("关闭Grafana用户导出对话框")
        
        except Exception as e:
            error_msg = f"启动Grafana用户导出对话框时发生错误：{str(e)}"
            self.log_message(error_msg)
            QMessageBox.critical(
                self,
                "错误",
                error_msg
            )
            logger.error(error_msg)
    
    def show_about_dialog(self):
        """显示关于对话框"""
        QMessageBox.about(
            self,
            "关于",
            f"{self.config['app']['name']} v{self.config['app']['version']}\n\n"
            "Zabbix管理工具 - 提供主机监控项和触发器创建、批量修改主机名和Grafana用户导出功能"
        )
    
    def check_api_connected(self):
        """检查API连接"""
        if not self.api:
            self.log_message("错误: 未连接到Zabbix API，请先登录")
            QMessageBox.warning(self, "未连接", "请先连接到Zabbix API。")
            return False
        return True 